{% extends 'base.html' %}
{% block content %}

<style>
.no_padding {
    padding-left: 0px;
    padding-right: 0px;
}


#scrollable-dropdown-menu .tt-dropdown-menu {
  max-height: 150px;
  overflow-y: auto;
}

.twitter-typeahead, .tt-hint, .tt-input, .tt-menu { width: 100%; }

.tt-query {
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}

.tt-hint {
    color: #999;
}

.tt-menu {
    /* width: 422px; */
    margin-top: 12px;
    padding: 8px 0;
    background-color: #fff;
    border: 1px solid #ccc;
    border: 1px solid rgba(0, 0, 0, 0.2);
    border-radius: 8px;
    box-shadow: 0 5px 10px rgba(0,0,0,.2);
}

.tt-suggestion {
    padding: 3px 20px;
    /* font-size: 18px; */
    line-height: 24px;
}

.tt-suggestion.tt-is-under-cursor {
    color: #fff;
    background-color: #0097cf;

}

.tt-suggestion p {
    margin: 0;
}

label.radio {
  margin-left: 20px;
}
</style>

<ul class="breadcrumb">
  <li><a href="{% url 'list_scans_view' %}">scans</a></li>
  <li class="active">add new scan</li>
</ul>

<div class="container">
  <form action="{% url 'add_scan_def_view' %}" method="post" class="form-horizontal">
    <legend>Add a new scan definition</legend>
    {% csrf_token %}

    <!-- Title -->
    <div class="form-group">
      <label class="col-sm-2 control-label" for="id_title">Title</label>
      <div class="col-sm-5">
        <input id="id_title" name="title" type="text" placeholder="Enter a title..." required class="form-control"/>
      </div>
    </div>

    <!-- Description -->
    <div class="form-group">
      <label class="col-sm-2 control-label" for="id_description">Description</label>
      <div class="col-sm-5">
        <textarea cols="40" id="id_description" name="description" placeholder="Enter a quick description..." rows="5" class="form-control"></textarea>
      </div>
    </div>

    <!-- Scan Type -->
    <div class="form-group">
      <label class="col-sm-2 control-label" for="id_scan_type">Scan Type</label>
      <div class="col-sm-4">
        <div class="col-sm-6 no_padding">
          <div class="btn-group btn-group-sm btn-scantype" data-toggle="buttons">
            <label class="btn btn-success active" id="lbl_scan_type_ondemand">
              <input type="radio" name="scan_type" value="single" id="id_scan_type_ondemand" autocomplete="off" checked="checked"> On-demand
            </label>
            <label class="btn btn-primary" id="lbl_scan_type_periodic">
              <input type="radio" name="scan_type" value="periodic" id="id_scan_type_periodic" autocomplete="off"> Periodical
            </label>

          </div>
        </div>
        <!-- Periodicity options -->
        <div class="col-sm-3 no_padding">
          <input class="form-control form-control-sm" type="text" placeholder="freq." id="id_scan_periodic_freq" name="every" disabled>
        </div>
        <div class="col-sm-3 no_padding">
          <select class="form-control form-control-sm" id="id_scan_periodic_period" name="period" disabled>
            <option value="days">Days</option>
            <option value="hours">Hours</option>
            <option value="minutes">Minutes</option>
            <option value="seconds">Seconds</option>
          </select>
        </div>
      </div>
    </div>

    <!-- Scan starting -->
    <div class="form-group">
      <label class="col-sm-2 control-label" for="id_enabled">Start scan</label>
      <div class="col-sm-4">
        <div class="col-sm-7 no_padding">
          <div class="btn-group btn-group-sm btn-scanrun" data-toggle="buttons">
            <label class="btn btn-success active" id="lbl_start_later">
              <input type="radio" name="start_scan" id="id_start_later" autocomplete="off" checked="checked" value="later">Later
            </label>
            <label class="btn btn-primary" id="lbl_start_now">
              <input type="radio" name="start_scan" id="id_start_now" autocomplete="off" value="now">Now
            </label>
            <label class="btn btn-primary" id="lbl_start_scheduled">
              <input type="radio" name="start_scan" id="id_start_scheduled" autocomplete="off" value="scheduled">Scheduled at
            </label>
          </div>
        </div>
        <div class="col-sm-5 controls input-append date no_padding" id="id_scheduled_at_div" >
          <input id="id_scheduled_at" name="scheduled_at" type="text" class="form-control form-control-sm" placeholder="pick a date" disabled/>
        </div>
      </div>
    </div>

    <!-- Asset selection -->
    <div class="form-group">
      <label class="col-sm-2 control-label" for="id_assets_list">Search asset(s):</label>
      <div class="col-sm-5 has-feedback">
        <div id="scrollable-dropdown-menu">
          <input class="typeahead form-control" type="text" placeholder="Search assets">
          <i class="form-control-feedback glyphicon glyphicon-search"></i>
        </div>
      </div>
    </div>

    <!-- Selected assets and asset groups -->
    <div class="form-group">
      <label class="col-sm-2 control-label" for="id_assets_list">Asset(s) selected:</label>
      <div class="col-sm-5">
        <div class="custom-control custom-checkbox cbx_assets">
          <!-- list of selected assets -->
        </div>
      </div>
    </div>

    <!-- Filter scan policies by engine name -->
    <div class="form-group" id="engine-buttons">
      <label class="col-sm-2 control-label" for="id_engine_name">Filter by Engine:</label>
      <div class="col-sm-5">
        <div class="btn-group btn-group-sm" role="group" data-toggle="buttons">
          <label class="btn btn-primary" engineId="0">
            <input type="radio" autocomplete="off">
            All
          </label>
          {% for engine in scan_engines %}
            <label class="btn btn-primary" engineId="{{ engine.id }}">
              <input type="radio" autocomplete="off">
              {{ engine.name }}
            </label>
          {% endfor %}
        </div>
      </div>
    </div>

    <!-- Filter scan policies by scan category -->
    <div class="form-group" id="category-buttons">
      <label class="col-sm-2 control-label" for="id_scan_category">Or, Filter by Category:</label>
      <div class="col-sm-5">
        <div class="btn-group btn-group-sm" role="group" data-toggle="buttons">
          <label class="btn btn-primary" categoryId="0">
            <input type="radio" autocomplete="off">All
          </label>
          {% for category in scan_cats %}
          <label class="btn btn-primary" categoryId="{{ category.id }}">
            <input type="radio" autocomplete="off">{{ category.name }}
          </label>
          {% endfor %}
        </div>
      </div>
    </div>

    <!-- Scan policy selection -->
    <div class="form-group hidden" id="policies-div">
      <label class="col-sm-2 control-label" for="id_engine_policy">Select Policy:</label>
      <div class="col-sm-4 custom-control custom-radio">
        {% for policy in scan_policies %}
        <label class="radio" label-id="{{ policy.id }}">
          <input type="radio" class="custom-control-input" name="engine_policy" id="id_engine_policy_{{ policy.id }}" value="{{ policy.id }}" engine-name="{{ policy.engine.name }}" required/>{{ policy.name }} - {{ policy.engine }}
        </label>
        {% endfor %}
      </div>
    </div>

    <!-- Engine instance selection -->
    <!-- Displayed when a policy is selected-->
    <div class="form-group hidden" id="engine-div">
      <label class="col-sm-2 control-label" for="id_engine_id">Select Engine:</label>
      <div class="col-sm-4">
        <select id="id_engine" name="engine_id" class="form-control" required>
          <!-- autofilled by jQuery -->
        </select>
      </div>
    </div>
    <div class="form-group hidden submit-div">
      <div class="col-sm-2">
      </div>
      <div class="col-sm-4">
        <button type="submit" class="btn btn-warning col-sm-12">Create a new scan</button>
      </div>
    </div>
  </form>
</div>

<script>

  _selected_assets = [];
  _id_asset = 1;
  $(function() {

    // toggle scan type radio buttons styles
    $('div.btn-scantype').click(function (e) {
      if (e.target.id != $('div.btn-scantype label.active').attr('id')){
        $('div.btn-scantype label:not(.active) input').attr("checked", "checked");
        $('div.btn-scantype label.active input').removeAttr("checked", "checked");

        $('div.btn-scantype label.active').removeClass("btn-success");
        $('div.btn-scantype label.active').addClass("btn-primary");
        $('div.btn-scantype label:not(.active)').removeClass("btn-primary");
        $('div.btn-scantype label:not(.active)').addClass("btn-success");

        if (e.target.id == "lbl_scan_type_periodic"){
          $('#id_scan_periodic_freq').removeAttr("disabled");
          $('#id_scan_periodic_period').removeAttr("disabled");
        } else {
          $('#id_scan_periodic_freq').attr("disabled","disabled");
          $('#id_scan_periodic_period').attr("disabled","disabled");
        }
      }
    });

    // toggle scan start radio buttons styles
    $('div.btn-scanrun').click(function (e) {
      if (e.target.id != $('div.btn-scanrun label.active').attr('id')){
        $('div.btn-scanrun label input').removeAttr("checked", "checked");
        $(e.target).find('input').attr("checked", "checked");

        $('div.btn-scanrun label').removeClass("btn-success");
        $('div.btn-scanrun label').addClass("btn-primary");
        $(e.target).removeClass("btn-primary");
        $(e.target).addClass("btn-success");

        if (e.target.id == "lbl_start_scheduled"){
          $('#id_scheduled_at').removeAttr("disabled");
        } else {
          $('#id_scheduled_at').attr("disabled", "disabled");
        }
        $('div.btn-scanrun label input').removeAttr("disabled")
      }
    });

    // datepicker for scheduled scans
    $("#id_scheduled_at").datetimepicker({
      minuteStep: 5,
      autoclose: true,
      language: 'en',
      format: 'yyyy-mm-dd hh:ii:ss',
      clearBtn: true,
      //pickerPosition: 'bottom-right',
      showMeridian: false,
      todayHighlight: true
    });

    localStorage.clear();
    var assets = new Bloodhound({
      // datumTokenizer: Bloodhound.tokenizers.obj.whitespace,
      datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      prefetch: "{% url 'list_assets_api' %}",
      ttl:0,
      remote: {
        url: "{% url 'list_assets_api' %}?q=%QUERY",
        wildcard: '%QUERY'
      }
    });

    $('#scrollable-dropdown-menu .typeahead').typeahead({
      hint: true,
      highlight: true,
      minLength: 2
    }, {
      name: 'assets',
      display: 'value',
      //limit: 5,
      source: assets.ttAdapter(),
      templates: {
        empty: function(data) {
          return '<div class="noitems"> No items found</div>';
        },
        suggestion: function(data) {
          if (data.format == "asset"){
            return '<div>' + data.value + ' - '+ data.name + '</div>';
          } else {
            return '<div> [Group] ' + data.value + ' - '+ data.name + '</div>';
          }
        }
      }
    }).bind("typeahead:selected", function(e, datum, name) {
      // append the asset to the list
      if (_selected_assets.indexOf(datum["value"]) == -1){
        if (datum["format"] == "asset") {
          _selected_assets.push(datum["value"]);
          _id_asset += 1;
          $('div.cbx_assets').append("<label for='id_assets_list_"+_id_asset+"' class='custom-control-label'>\
            <input id='id_assets_list_"+_id_asset+"' class='custom-control-input' name='assets_list' type='checkbox' value='"+datum["id"]+"' checked/> "+e.target.value+"</label><br/>");
        } else {
          _selected_assets.push(datum["value"]);
          _id_asset += 1;
          $('div.cbx_assets').append("<label for='id_assetgroups_list_"+_id_asset+"' class='custom-control-label'>\
            <input id='id_assetgroups_list_"+_id_asset+"' class='custom-control-input' name='assetgroups_list' type='checkbox' value='"+datum["id"]+"' checked/> "+e.target.value+" (group)</label><br/>");
        }
      }
    });

    // Filter scan policy by engines & categories
    var policies_list = {{ scan_policies_json | safe }};
    var hidden_policies_by_cat = [];
    var hidden_policies_by_engine = [];
    $('#category-buttons').bind('change', function(e){
      $('#policies-div').removeClass('hidden');
      $("html, body").animate({ scrollTop: $(document).height() }, "slow");
      $('#engine-buttons > div > div > label').removeClass('active');
      $('#engine-buttons > div > div > label[engineid=0]').addClass('active');

      active_cat = parseInt($(e.target).attr('categoryId'));
      hidden_policies_by_cat = [];

      if (active_cat != 0) {
        var i, j;

        // loop on all policies
        for (i = 0; i < policies_list.length; ++i){
          scopes = policies_list[i]["scopes"];
          if (scopes.indexOf(active_cat) == -1) {
            if (hidden_policies_by_cat.indexOf(policies_list[i]["id"]) === -1){
              hidden_policies_by_cat.push(policies_list[i]["id"]);
            }
          };
        }
      }

      //list policies with categoryId in scopes
      labels = $("#policies-div").find('div > label');
      for (i = 0; i < labels.length; ++i){
        if (hidden_policies_by_cat.indexOf(parseInt($(labels[i]).attr('label-id'))) > -1){
          $(labels[i]).addClass('hidden');
        } else {
          $(labels[i]).removeClass('hidden');
        }
      }

    }); //End of $('#category-buttons').bind('change')

    $('#engine-buttons').bind('change', function(e){
      $('#policies-div').removeClass('hidden');
      $("html, body").animate({ scrollTop: $(document).height() }, "slow");
      $('#category-buttons > div > div > label').removeClass('active');
      $('#category-buttons > div > div > label[categoryid=0]').addClass('active');

      active_engine = parseInt($(e.target).attr('engineId'));
      hidden_policies_by_engine = [];

      if (active_engine != 0) {
        var i, j;

        // loop on all policies
        for (i = 0; i < policies_list.length; ++i){
          if( policies_list[i]['engine'] != active_engine){
            hidden_policies_by_engine.push(policies_list[i]['id'])
          }
        }
      }

      //list policies with matching categoryId
      labels = $("#policies-div").find('div > label');
      for (i = 0; i < labels.length; ++i){
        if (hidden_policies_by_engine.indexOf(parseInt($(labels[i]).attr('label-id'))) > -1){
          $(labels[i]).addClass('hidden');
        } else {
          $(labels[i]).removeClass('hidden');
        }
      }
    }); //End of $('#engine-buttons').bind('change')

    // unhide the engine select until a scan policy is selected
    $("#policies-div").change(function(e){
      $('#engine-div').removeClass('hidden');
      $('div.submit-div').removeClass('hidden');
      $("html, body").animate({ scrollTop: $(document).height() }, "slow");
    });

    // List appropriate engine instances depending on scan policy
    engine_list = {{scan_engines_json|safe}}
    $("[name='engine_policy']").change(function(e){
      engine_name = e.currentTarget.getAttribute('engine-name');
      $('select#id_engine').empty();
      $('select#id_engine').append("<option value='-1'>---- random (by default) ----</option>");
      for (i = 0; i< engine_list.length; i++){
        if(engine_list[i]["engine__name"] == engine_name){
          $('select#id_engine').append($('<option>', {
              value: engine_list[i]['id'],
              text: engine_list[i]['name']
            })
          );
        }
      }
    });

  }); //End of jQuery ready

</script>

{% endblock %}
